/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.bpm.engine.impl.cfg.multitenant;

import com.je.bpm.engine.ActivitiException;

import javax.sql.DataSource;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

/**
 * A {@link DataSource} implementation that switches the currently used datasource based on the
 * current values of the {@link TenantInfoHolder}.
 * <p>
 * When a {@link Connection} is requested from this {@link DataSource}, the correct {@link DataSource}
 * for the current tenant will be determined and used.
 * <p>
 * Heavily influenced and inspired by Spring's AbstractRoutingDataSource.
 *
 * @deprecated multi-tenant code will be removed in future version of Activiti and Activiti Cloud
 */
@Deprecated
public class TenantAwareDataSource implements DataSource {

    protected TenantInfoHolder tenantInfoHolder;
    protected Map<Object, DataSource> dataSources = new HashMap<Object, DataSource>();

    public TenantAwareDataSource(TenantInfoHolder tenantInfoHolder) {
        this.tenantInfoHolder = tenantInfoHolder;
    }

    public void addDataSource(Object key, DataSource dataSource) {
        dataSources.put(key, dataSource);
    }

    public void removeDataSource(Object key) {
        dataSources.remove(key);
    }

    @Override
    public Connection getConnection() throws SQLException {
        return getCurrentDataSource().getConnection();
    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        return getCurrentDataSource().getConnection(username, password);
    }

    protected DataSource getCurrentDataSource() {
        String tenantId = tenantInfoHolder.getCurrentTenantId();
        DataSource dataSource = dataSources.get(tenantId);
        if (dataSource == null) {
            throw new ActivitiException("Could not find a dataSource for tenant " + tenantId);
        }
        return dataSource;
    }

    @Override
    public int getLoginTimeout() throws SQLException {
        return 0; // Default
    }

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        return Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
    }

    @Override
    @SuppressWarnings("unchecked")
    public <T> T unwrap(Class<T> iface) throws SQLException {
        if (iface.isInstance(this)) {
            return (T) this;
        }
        throw new SQLException("Cannot unwrap " + getClass().getName() + " as an instance of " + iface.getName());
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return iface.isInstance(this);
    }

    public Map<Object, DataSource> getDataSources() {
        return dataSources;
    }

    public void setDataSources(Map<Object, DataSource> dataSources) {
        this.dataSources = dataSources;
    }

    // Unsupported //////////////////////////////////////////////////////////
    @Override
    public PrintWriter getLogWriter() throws SQLException {
        throw new UnsupportedOperationException();
    }

    @Override
    public void setLogWriter(PrintWriter out) throws SQLException {
        throw new UnsupportedOperationException();
    }

    @Override
    public void setLoginTimeout(int seconds) throws SQLException {
        throw new UnsupportedOperationException();
    }

}
